//
//  PlantDetailTableViewController.m
//  PlotMate
//
//  Created by Brian Boyle on 30/03/2012.
//  Copyright (c) 2012 Brian Boyle. All rights reserved.
//

#import "PlantDetailTableViewController.h"
#import "PlantSet+CRUD.h"
#import "SavePlantSetTableViewController.h"
#import "AppDelegate.h"
#import "AddToPlotViewController.h"
#import "Plot+CRUD.h"

@interface PlantDetailTableViewController()
@property (nonatomic, strong) MKNumberBadgeView *badgeView;
@property (nonatomic, weak) UIImageView *plantImageView;
@property (nonatomic, strong) NSManagedObjectContext *context;
@property (nonatomic) CGPoint bgOrigin;
@end

@implementation PlantDetailTableViewController

@synthesize plant = _plant;
@synthesize badgeView = _badgeView;
@synthesize plantImageView = _plantImageView;
@synthesize context = _context;
@synthesize bgOrigin = _bgOrigin;



#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.context = [(AppDelegate*)[UIApplication sharedApplication].delegate managedObjectContext];
    
    //Set the background image
    UIImageView *tempImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"paper.png"]];
    [tempImageView setFrame:self.tableView.frame]; 
    self.tableView.backgroundView = tempImageView;
    
    //Initialise the badge view for planting sets
    self.badgeView = [[MKNumberBadgeView alloc] init];
    self.badgeView.hideWhenZero = YES;
}


-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //Set up the badge for set count
    CGRect frame = CGRectMake(220, 3, 40, 35);
    self.badgeView.frame = frame;
    [self.navigationController.navigationBar addSubview:self.badgeView];
    self.badgeView.value =[PlantSet countPlantsPlantSetArray];
    self.badgeView.fillColor = [UIColor colorWithRed:0.4 green:0.522 blue:0.129 alpha:1];
}


-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.badgeView removeFromSuperview];
}


- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

/*Perform animation when a user adds a plant to a planting set.*/
-(void)scaleAndTranslateImageToSetsButton:(UIImageView *)imageView withDelay:(CGFloat)delay plantSets:(NSArray *)plantSets
{ 
    //Create a ghost image view with opacity of 50%
    UIImageView *ghostImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[self.plant.name stringByAppendingString:@"_L"]]];
    ghostImageView.frame = CGRectMake(imageView.frame.origin.x, imageView.frame.origin.y + 35, imageView.frame.size.width, imageView.frame.size.height);
    
    ghostImageView.alpha = 0.5;
    [self.view addSubview:ghostImageView];
    
    //Scale and move the image to the top right of the screen.
    CGAffineTransform translate = CGAffineTransformMakeTranslation(125, -120);
    CGAffineTransform scale = CGAffineTransformMakeScale(0.1, 0.1);
    CGAffineTransform transform =  CGAffineTransformConcat(scale, translate);

    [UIView animateWithDuration:1.0 delay:0 options:UIViewAnimationCurveEaseInOut animations:^{
        // animate it to the identity transform (100% scale)
        ghostImageView.transform = transform;
        
    } completion:^(BOOL finished ){ 
        //Update the planting set badge count and remove the ghost image from the view
        self.badgeView.value = [plantSets count];
        [ghostImageView removeFromSuperview];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 6;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.row == 0){
        return 44;
    }
    else if(indexPath.row == 1){
        return 215;
        
    }else if(indexPath.row == 2){
        //Configure the description cell so that the height will adjust for the wrapping text
        UIFont *cellFont = [UIFont fontWithName:@"ArialMT" size:17.0];
        CGSize constraintSize = CGSizeMake(280.0f, MAXFLOAT);
        CGSize labelSize = [self.plant.desc sizeWithFont:cellFont constrainedToSize:constraintSize lineBreakMode:UILineBreakModeWordWrap];
        if(labelSize.height < 44){
            labelSize.height = labelSize.height + 60;
        }
        return labelSize.height + 5;
    }
    return 59;

   
}

-(void)setButtonLabelFonts:(UITableViewCell *)cell
{
    UILabel *favLabel = (UILabel *)[cell viewWithTag:3];
    favLabel.font = [UIFont fontWithName:@"MV Boli" size:12];
    
    //Change the text of the favourite button based on whether the plant is a favourite or not.
    if([self.plant.isFavourite isEqualToNumber:[NSNumber numberWithBool:YES]]){
        favLabel.text = @"Remove Favourite";
    }else{
        favLabel.text = @"Add Favourite";
    }
    
    UILabel *setLabel = (UILabel *)[cell viewWithTag:4];
    setLabel.font = [UIFont fontWithName:@"MV Boli" size:12];
    
    UILabel *plotLabel = (UILabel *)[cell viewWithTag:5];
    plotLabel.font = [UIFont fontWithName:@"MV Boli" size:12];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    UITableViewCell *cell;
    static NSString *CellIdentifier;
    if(indexPath.row == 0){
        CellIdentifier = @"titleCell";
    }else  if(indexPath.row == 1){
        CellIdentifier = @"imageCell";
    }else{
        CellIdentifier = @"detailCell";
    }
    
    cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    if(indexPath.row == 0){
        UILabel *plantNameLabel = (UILabel *)[cell viewWithTag:1];
        plantNameLabel.text = self.plant.name;
        plantNameLabel.font = [UIFont fontWithName:@"Sketch Block" size:24];
        plantNameLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    }if(indexPath.row == 1){
        self.plantImageView = (UIImageView *)[cell viewWithTag:1];
        self.plantImageView.image = [UIImage imageNamed:[self.plant.name stringByAppendingString:@"_L"]];
        [self setButtonLabelFonts:cell];
    }else if(indexPath.row == 2){
        cell.textLabel.text = @"Description";
        cell.textLabel.font = [UIFont fontWithName:@"Sketch Block" size:16];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
        //Wrapping
        cell.detailTextLabel.numberOfLines = 0;
        cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.detailTextLabel.text = self.plant.desc;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    }else if(indexPath.row == 3){
        cell.textLabel.text = @"Soil";
        cell.textLabel.font = [UIFont fontWithName:@"Sketch Block" size:16];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
        //Wrapping
        cell.detailTextLabel.numberOfLines = 0;
        cell.detailTextLabel.lineBreakMode = UILineBreakModeWordWrap;
        cell.detailTextLabel.text = self.plant.soil;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    }else if(indexPath.row == 4){
        cell.textLabel.text = @"Sow";
        cell.textLabel.font = [UIFont fontWithName:@"Sketch Block" size:16];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
        
        cell.detailTextLabel.text = self.plant.sowMonths;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    }else if(indexPath.row == 5){
        cell.textLabel.text = @"Harvest";
        cell.textLabel.font = [UIFont fontWithName:@"Sketch Block" size:16];
        cell.textLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
        
        cell.detailTextLabel.text = self.plant.harvestMonths;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:0 green:0.275 blue:0.118 alpha:1];
    }
    
    cell.backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
    cell.backgroundColor = [UIColor clearColor];
    
    return cell;
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    //We have not title for sections so return nil
    return nil;
}

#pragma mark - Button Actions

/*Add a plant to a planting set*/
- (IBAction)addToSetPressed:(UIButton *)sender 
{
    NSArray *plantSets = [PlantSet addPlantNameToNSUserDefaults:self.plant.name];
    if(plantSets == nil){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Plant already in Set" message:[NSString stringWithFormat:@"%@ is already added to the Planting Set", self.plant.name] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        [self scaleAndTranslateImageToSetsButton:self.plantImageView withDelay:0 plantSets:plantSets];
        
    }
}

/*Add a plant as a favourite*/
- (IBAction)favouritePressed:(UIButton *)sender 
{
    UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
    UILabel *favLabel = (UILabel *)[cell viewWithTag:3];
    
    if([self.plant.isFavourite isEqualToNumber:[NSNumber numberWithBool:NO]] ){
        self.plant.isFavourite = [NSNumber numberWithBool:YES];
        favLabel.text = @"Remove Favourite";
    } else {
        self.plant.isFavourite = [NSNumber numberWithBool:NO];
        favLabel.text = @"Add Favourite";
    }
}

- (IBAction)savePlantSetPressed:(UIBarButtonItem *)sender 
{
    NSMutableArray *plantSetArray = [PlantSet getPlantSetFromNSUserDefaults];
    //Show an alert if there are no plants in the NSUserDefualts plant set array
    if(plantSetArray == nil || [plantSetArray count] == 0){
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Oops!" message:@"There is nothing to save! Please add a plant to the Planting Set first" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }else{
        NSString *addToExistingText;
        if ([[PlantSet getAllPlantSetsInContext:self.context] count] != 0) {
            addToExistingText = @"Add to existing Set";
        }
        UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Create new Set", addToExistingText, nil];
        
        actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
        [actionSheet dismissWithClickedButtonIndex:0 animated:YES];
        [actionSheet showFromTabBar:self.tabBarController.tabBar];
    }
}

- (IBAction)addToPlotPressed:(UIButton *)sender 
{
    if([Plot checkIfPlotsExistInContext:self.context] == YES){
        [self performSegueWithIdentifier:@"addToPlotSegue" sender:self];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Plots!" message:@"Please create a plot first" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    }
}


-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([[PlantSet getAllPlantSetsInContext:self.context] count] != 0) {
        switch (buttonIndex) {
            case 0:
                [self performSegueWithIdentifier:@"savePlantSetSegue" sender:self];
                break;
            case 1:
                [self performSegueWithIdentifier:@"addToExistingPlantSetSegue" sender:self];
                break;
            default:
                break;
        }
    }else{
        switch (buttonIndex) {
            case 0:
                [self performSegueWithIdentifier:@"savePlantSetSegue" sender:self];
                break;
                
            default:
                break;
        }
    }
}

-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if([segue.identifier isEqualToString:@"addToExistingPlantSetSegue"]){
        UINavigationController *navCon = (UINavigationController *)segue.destinationViewController;
        SavePlantSetTableViewController *savePlantSetVC = [navCon.viewControllers objectAtIndex:0];
        savePlantSetVC.addtoExistingPlantSet = YES;
    }else if([segue.identifier isEqualToString:@"addToPlotSegue"]){
        //Set the current plant on the viewController to add it to a plot
        UINavigationController *navCon = (UINavigationController *)segue.destinationViewController;
        AddToPlotViewController *addToPlotVC = [navCon.viewControllers objectAtIndex:0];
        [addToPlotVC setPlantsToAdd:[NSArray arrayWithObject:self.plant]];
    }
}

@end
